<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>proxy-监听对象属性的操作</title>
</head>
<body>
  
  <script>

    const obj = {
      name: "why",
      age: 18,
      height: 1.88
    }
    
    const keys = Object.keys(obj)
    for (const key of keys) {
      
      let value = Object[key]
      Object.defineProperty(obj, key, {
        set: function(newValue) {
          console.log(`监听：给${key}设置了新值${newValue}`)      
          value = newValue
        },
        get: function(){
          console.log(`监听:获取${key}的值`)
          console.log(value)
          return value
        }
      })
    }

    obj.age = 17
    console.log(obj.age)


    //ES6写法

    const objProxy = new Proxy(obj, {
      set: function(target, p, newValue) {
        console.log(`监听：给${p}设置了新值${newValue}`)      
        target[p] = newValue
      },
      get: function(target, p) {
        console.log(`监听:获取${p}的值`)
        return target[p]
      },
      //删除
      deleteProperty: function(target, key) {
        console.log(`监听: 监听删除${key}属性`)
        delete obj.name
      },
      //包含
      has: function(target, key) {
        console.log(`监听: 监听in判断 ${key}属性`)
        return key in target
      }
    })
    
    objProxy.address = "广州市"
    console.log(objProxy.address)
    
    console.log("age" in objProxy)


  </script>
</body>
</html>